<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <!-- 主表单区域 -->
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="8">
            <a-form-model-item label="营销订单号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="orderCode">
              <tsl-select-trade-order
                :status="999"
                :isCalcCost="0"
                v-model="model.orderCode"
                @change="handleTradeOrderChange"
              />
            </a-form-model-item>
          </a-col>

          <a-col :span="8">
            <a-form-model-item label="客户类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="customerCategory">
              <a-input v-model="model.customerCategory" placeholder="请输入客户类型"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="客户" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="customerId">
              <j-dict-select-tag type="list" disabled v-model="model.customerId" dictCode="erp_customer,name,id" />
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="单据编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="code">
              <a-input v-model="model.code" placeholder="系统自动生成" disabled></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="业务员" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="salesman">
              <a-input v-model="model.salesman" placeholder="请输入业务员"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="产品类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="productType">
              <j-dict-select-tag
                type="list"
                @change="onChangeProductType"
                v-model="model.productType"
                dictCode="product_type"
                placeholder="请选择产品类型"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="6" v-show="model.productType == 1">
            <a-form-model-item label="是否自动罐装" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="isAutoBottled">
              <j-dict-select-tag
                type="radio"
                v-model="model.isAutoBottled"
                dictCode="yes_no"
                placeholder="请选择是否自动罐装"
              />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
    <!-- 子表单区域 -->
    <a-tabs v-model="activeKey" @change="handleChangeTabs">
      <a-tab-pane tab="订单核算子表" :key="refKeys[0]" :forceRender="true">
        <j-vxe-table
          keep-source
          :ref="refKeys[0]"
          :loading="tslSaleCostDetailTable.loading"
          :columns="tslSaleCostDetailTable.columns"
          :dataSource="tslSaleCostDetailTable.dataSource"
          :maxHeight="300"
          :disabled="formDisabled"
          :rowNumber="true"
          :rowSelection="true"
          :toolbar="true"
        />
      </a-tab-pane>
    </a-tabs>
  </a-spin>
</template>

<script>
import { getAction } from '@/api/manage'
import { JVxeTableModelMixin } from '@/mixins/JVxeTableModelMixin.js'
import { JVXETypes } from '@/components/jeecg/JVxeTable'
import { getRefPromise, VALIDATE_FAILED } from '@/components/jeecg/JVxeTable/utils/vxeUtils.js'
import { validateDuplicateValue } from '@/utils/util'
import JFormContainer from '@/components/jeecg/JFormContainer'
import TslSelectTradeOrder from '../../../components/tsl/TslSelectTradeOrder.vue'

export default {
  name: 'TslSaleCostForm',
  mixins: [JVxeTableModelMixin],
  components: {
    JFormContainer,
    TslSelectTradeOrder,
  },
  data() {
    return {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      model: {},
      // 新增时子表默认添加几行空数据
      addDefaultRowNum: 1,
      validatorRules: {},
      refKeys: ['tslSaleCostDetail'],
      tableKeys: ['tslSaleCostDetail'],
      activeKey: 'tslSaleCostDetail',
      // 订单核算子表
      tslSaleCostDetailTable: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: '产品名称',
            key: 'productBatchNo',
            type: JVXETypes.normal,
            width: '200px',
          },
          {
            title: '产品规格',
            key: 'productSpec',
            type: JVXETypes.normal,
            width: '100px',
          },
          {
            title: '件吨',
            key: 'piecePerTon',
            type: JVXETypes.normal,
            width: '80px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '原料成本',
            key: 'material',
            type: JVXETypes.normal,
            width: '100px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '包材成本',
            key: 'packageMaterials',
            type: JVXETypes.normal,
            width: '100px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '中间费用',
            key: 'midExpenses',
            type: JVXETypes.input,
            width: '100px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '合计',
            key: 'total',
            type: JVXETypes.normal,
            width: '100px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '出厂价',
            key: 'exWorksPrice',
            type: JVXETypes.normal,
            width: '100px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '陆运费',
            key: 'landFreight',
            type: JVXETypes.normal,
            width: '80px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          // {
          //   title: '不干胶贴',
          //   key: 'adhesiveStickers',
          //   type: JVXETypes.normal,
          //   width: '80px',
          //   placeholder: '请输入${title}',
          //   defaultValue: '',
          // },
          {
            title: '海运费',
            key: 'seaFreight',
            type: JVXETypes.normal,
            width: '80px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '认证费用',
            key: 'cocoExpenses',
            type: JVXETypes.normal,
            width: '80px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '版费',
            key: 'royalty',
            type: JVXETypes.normal,
            width: '80px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '保费',
            key: 'insurancePremium',
            type: JVXETypes.normal,
            width: '80px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '印刷费',
            key: 'printingFee',
            type: JVXETypes.normal,
            width: '80px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '佣金',
            key: 'commission',
            type: JVXETypes.normal,
            width: '80px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '其他',
            key: 'other',
            type: JVXETypes.normal,
            width: '80px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '合计',
            key: 'total2',
            type: JVXETypes.normal,
            width: '100px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '合同价',
            key: 'contractPrice',
            type: JVXETypes.normal,
            width: '100px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '税前合同价(RMB)',
            key: 'contractPriceBeforeTax',
            type: JVXETypes.input,
            width: '200px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '差价(RMB)',
            key: 'difference',
            type: JVXETypes.input,
            width: '150px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '汇率',
            key: 'exchangeRate',
            type: JVXETypes.input,
            width: '100px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '实际中间费用',
            key: 'actualMidExpenses',
            type: JVXETypes.input,
            width: '200px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '订单吨数',
            key: 'ywTon',
            type: JVXETypes.normal,
            width: '100px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '提成',
            key: 'salesCommission',
            type: JVXETypes.input,
            width: '100px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
        ],
      },
      url: {
        add: '/sale/tslSaleCost/add',
        edit: '/sale/tslSaleCost/edit',
        queryById: '/sale/tslSaleCost/queryById',
        tslSaleCostDetail: {
          list: '/sale/tslSaleCost/queryTslSaleCostDetailByMainId',
          listByOrderCode: '/sale/tslSaleCost/queryTslSaleCostDetailByOrderCode',
        },
      },
    }
  },
  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false,
    },
  },
  computed: {
    formDisabled() {
      return this.disabled
    },
  },
  created() {},
  methods: {
    onChangeProductType() {
      if (this.model.productType != 1) {
        this.model.isAutoBottled = 0
      }
    },
    handleTradeOrderChange(code, data) {
      if (data && data.length > 0) {
        let row = data[0]
        console.log('TradeOrderCode', code, row, this.model.orderCode)
        this.model.customerCategory = row.customer
        this.model.customerId = row.customerId
        //粉类
        this.model.productType = row.productType

        this.model.salesman = row.salesman
        getAction(this.url.tslSaleCostDetail.listByOrderCode, { code: row.code }).then((res) => {
          console.log('获取营销订单关联的产品报价信息', res)
          if (res.success) {
            this.tslSaleCostDetailTable.dataSource = res.result
            this.$forceUpdate()
          }
        })
      }
    },
    addBefore() {
      this.tslSaleCostDetailTable.dataSource = []
    },
    getAllTable() {
      let values = this.tableKeys.map((key) => getRefPromise(this, key))
      return Promise.all(values)
    },
    /** 调用完edit()方法之后会自动调用此方法 */
    editAfter() {
      this.$nextTick(() => {})
      // 加载子表数据
      console.log('编辑', this.model)
      if (this.model.id) {
        let params = { id: this.model.id }
        this.requestSubTableData(this.url.tslSaleCostDetail.list, params, this.tslSaleCostDetailTable)
      }
    },
    //校验所有一对一子表表单
    validateSubForm(allValues) {
      return new Promise((resolve, reject) => {
        Promise.all([])
          .then(() => {
            resolve(allValues)
          })
          .catch((e) => {
            if (e.error === VALIDATE_FAILED) {
              // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
              this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
            } else {
              console.error(e)
            }
          })
      })
    },
    /** 整理成formData */
    classifyIntoFormData(allValues) {
      let main = Object.assign(this.model, allValues.formValue)
      return {
        ...main, // 展开
        tslSaleCostDetailList: allValues.tablesValue[0].tableData,
      }
    },
    validateError(msg) {
      this.$message.error(msg)
    },
  },
}
</script>

<style scoped></style>
